package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.Constant;
import com.example.demo.model.entity.ShopModel;
import com.example.demo.service.impl.ShopService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

@Controller
@RequestMapping(value = Constant.API_VERSION + "/shop")
public class ShopController {

    @Resource
    ShopService shopService;

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public ShopModel save(@RequestHeader("Authorization") String token, @RequestBody ShopModel shop) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        String pattern = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        boolean isMatch = Pattern.matches(pattern, shop.getPhone());
        if (!isMatch) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 400, "电话号码格式错误"));
        }
        String currentUid = new String(decoder.decodeBuffer(token), "UTF-8");
        shop.setShopId(UUID.randomUUID().toString());
        shop.setCreateTime(System.currentTimeMillis());
        shop.setCreateUid(currentUid);
        return shopService.save(shop);
    }

    @RequestMapping(value = "/{shop_id}", method = RequestMethod.DELETE)
    @ResponseBody
    public void delete(@RequestHeader("Authorization") String token, @PathVariable(value = "shop_id") String shopId) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        String currentUid = new String(decoder.decodeBuffer(token), "UTF-8");
        ShopModel shop = shopService.getByShopId(shopId);
        if (shop == null) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 400, "店铺不存在"));
        }
        shopService.delete(shopId);
    }


    @RequestMapping(value = "/{shop_id}", method = RequestMethod.PUT)
    @ResponseBody
    public ShopModel update(@RequestHeader("Authorization") String token, @PathVariable(value = "shop_id") String shopId, @RequestBody ShopModel model) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        String currentUid = new String(decoder.decodeBuffer(token), "UTF-8");
        ShopModel shop = shopService.getByShopId(shopId);
        if (!shop.getCreateUid().equals(currentUid)) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 403, "权限不足"));
        }
        if (shop == null) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 400, "店铺不存在"));
        }
        if (StringUtils.isNotEmpty(model.getShopName())) {
            shop.setShopName(model.getShopName());
        }
        if (StringUtils.isNotEmpty(model.getPhone())) {
            shop.setPhone(model.getPhone());
        }
        if (StringUtils.isNotEmpty(model.getAddress())) {
            shop.setAddress(model.getAddress());
        }
        if (StringUtils.isNotEmpty(model.getCityCode())) {
            shop.setCityCode(model.getCityCode());
        }
        return shopService.save(shop);
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getShopPage(@RequestParam(value = "page_size", defaultValue = "10") String pageSize, @RequestParam(value = "page_number", defaultValue = "1") String pageNumber,
                                  @RequestParam(value = "city_code", defaultValue = "") final String cityCode,
                                  @RequestParam(value = "keyword", defaultValue = "") final String keyword) throws Exception {
        Page<ShopModel> shopPage = shopService.getShopPage(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
//                if (StringUtils.isNotEmpty(cityCode)) {
//                    Path<Integer> cityCodePath = root.get("cityCode");
//                    predicateList.add(criteriaBuilder.equal(cityCodePath, cityCode));
//                }
                if (StringUtils.isNotEmpty(keyword)) {
                    Path<String> namePath = root.get("shopName");
                    predicateList.add(criteriaBuilder.like(namePath, "%" + keyword + "%"));
                }
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        }, new PageRequest(Integer.valueOf(pageNumber) - 1, Integer.valueOf(pageSize)));

        JSONObject result = new JSONObject();
        result.put("total", shopPage.getTotalElements());
        result.put("items", shopPage.getContent());
        return result;
    }

}
